package com.fzy.springsecurity2.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

/**
* @author fzy
* @version 1.0
* 创建时间：2024-10-08 14:24
*/

@Configuration
public class RedisConfig {
    // 默认过期时间 1 天
    public static final Duration DEFAULT_REDIS_EXPIRE = Duration.ofDays(1);

    /**
     * redis template.
     *
     * @param redisConnectionFactory factory
     * @return RedisTemplate
     */
    @Bean("redisTemplate")
    @ConditionalOnBean(ObjectMapper.class)
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory redisConnectionFactory, ObjectMapper objectMapper) {
        // 创建 RedisTemplate
        RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory); // 设置连接工厂

        // 创建 Jackson2JsonRedisSerializer
        //Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(objectMapper, Object.class);
        //Jackson2ClazRedisSerializer jackson2ClazRedisSerializer = new Jackson2ClazRedisSerializer(objectMapper);

        // 设置键值的序列化器
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());

        // 设置Hash 键值的序列化器
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new StringRedisSerializer());

        return redisTemplate;
    }
}

